<template>
	<view id="wrapper">
		<!-- 地图底框 -->
		<div id="container"></div>
		<div id="panel" v-if="showSearchResult"></div>
		<div id="walkPanel"></div>
		<!-- 其他界面 -->
		<div id="addressInfo" v-if="showAddressInfo">
			<u--form labelPosition="left" id="addressForm">
				<u-form-item label="起点">
					<u--text type="success" :text="nowAddress"></u--text>
				</u-form-item>
				<u-form-item label="终点">
					<view :prop="endAddress" :change:prop="test.onEndAddressChange"></view>
					<u--input id="endAddressInput" v-model="endAddress" disabledColor="#ffffff" placeholder="请输入终点"
						:prop="endAddress" :change:prop="test.onChange" border="bottom"></u--input>
				</u-form-item>
			</u--form>
			<div id="btn-group">
				<button type="primary" @tap="test.searchPlace" style="width: 80%;" size="mini">查找终点</button>
			</div>
		</div>
		<u-modal :show="showModal" title="确认目标地点" :showConfirmButton="true" :showCancelButton="true"
			@cancel="cancelModal" @confirm="confirmModal">
			<view class="slot-content">
				<rich-text :nodes="content"></rich-text>
			</view>
		</u-modal>
		<view :prop="nowLocation" :change:prop="test.onNowLocationChange"></view>
		<view :prop="targetPlaceLocation" :change:prop="test.onTargetPlaceLocationChange"></view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				nowAddress: '',
				endAddress: '',
				nowLocation: [],
				showModal: false,
				content: ``,
				// endLocation 当前选中的目的地的经纬度
				endLocation: [],
				// 为了能够调用子模块函数 通过触发targetPlaceLocation变化来调用
				targetPlaceLocation: [],
				showSearchResult: true,
				showAddressInfo: true,
				// 导航开始后开启的定时器id
				intervalId: null
			}
		},
		mounted() {
			this.getLocation()
		},
		methods: {
			//获取经纬度
			getLocation() {
				uni.getLocation({
					type: 'gcj02', //返回可以用于uni.openLocation的经纬度
					success: (res) => {
						let locationArr = []
						locationArr[0] = res.longitude
						locationArr[1] = res.latitude
						this.nowLocation = locationArr
					},
					fail: function(resp) {
						console.log(resp);
					}
				});
			},
			recevicePlaceSearchResult(data) {
				this.content = data.content;
				this.showModal = data.showModal
				this.endLocation = data.endLocation
			},
			receiveNowAddress(data) {
				this.nowAddress = data.nowAddress
			},
			// 隐藏地点搜索结果
			receiveShowSearchResult(data) {
				this.showSearchResult = data.showSearchResult
			},
			// 隐藏上半部分地点搜索界面 
			receiveShowAddressInfo(data) {
				this.showAddressInfo = data.showAddressInfo

				// 隐藏了搜索界面 说明开始导航了 开启一个定时器 每隔一定时间更新当前用户坐标
				if (this.intervalId === null) {
					this.intervalId = setInterval(() => {
						this.getLocation();
					}, 5000)
				}
			},
			cancelModal() {
				this.showModal = false;
			},
			confirmModal() {
				this.showModal = false;
				this.showSearchResult = false;
				this.targetPlaceLocation = this.endLocation;
			}
		}
	}
</script>

<script module="test" lang="renderjs">
	import AMapLoader from "@amap/amap-jsapi-loader";

	export default {
		name: "main",
		data() {
			return {
				map: '',
				placeSearch: '',
				nowLocation: [],
				endAddress: '',
				// 搜索要去的地点的关键词
				targetPlace: '',
				// 记录父级
				ownerInstance: null,
				// 目标地点位置
				targetPlaceLocation: [],
				// 记录下是否开始导航
				startNavigation: false,
			};
		},
		unmounted() {
			this.map?.destroy();
		},
		methods: {
			// 当service层中的endAddress值改变时调用
			onEndAddressChange(newValue, oldValue, ownerInstance, instance) {
				if ( newValue.length <= 0 ) {
					return;
				}
				this.endAddress = newValue
			},
			// 当service层中的nowLocation值改变时调用
			onNowLocationChange(newValue, oldValue, ownerInstance, instance) {
				if (newValue.length <= 0) {
					return;
				} 
				this.nowLocation = newValue
				this.ownerInstance = ownerInstance
				// 如果开始导航了 额外重新规划路径 但不重新绘制地图 否则只重新绘制地图
				if (this.startNavigation) {
					this.startWalking();
				} else {
					this.initAMap();
				}
			},
			onTargetPlaceLocationChange(newValue, oldValue, ownerInstance, instance) {
				if (newValue.length <= 0) {
					return;
				}
				this.targetPlaceLocation = newValue
				this.startWalking()
			},
			initAMap() {
				window._AMapSecurityConfig = {
					securityJsCode: "94697b54d35ad233d46a0364900a86c9",
				};
				AMapLoader.reset()
				AMapLoader.load({
						key: "bd1509b2c8644f4eb8ac504fbf4db856", // 申请好的Web端开发者Key，首次调用 load 时必填
						version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
						plugins: ["AMap.Scale",
							"AMap.PlaceSearch",
							"AMap.Geocoder"
						], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
					})
					.then((AMap) => {
						this.map = new AMap.Map("container", {
							// 设置地图容器id
							viewMode: "3D", // 是否为3D地图模式
							center: this.nowLocation, // 初始化地图中心点位置
							zoom: 17, // 初始化地图级别
						});
						let that = this;

						// JS版本API 逆向查询 根据经纬度反查询出初始地址
						AMap.plugin('AMap.Geocoder', function() {
							var geocoder = new AMap.Geocoder()
							var lnglat = that.nowLocation

							geocoder.getAddress(lnglat, function(status, result) {
								if (status === 'complete' && result.info === 'OK') {
									// result为对应的地理位置详细信息
									that.ownerInstance.callMethod('receiveNowAddress', {
										nowAddress: result.regeocode.formattedAddress
									})
								}
							})
						})

						// 地点搜索
						AMap.plugin(["AMap.PlaceSearch"], function() {
							that.placeSearch = new AMap.PlaceSearch({
								pageSize: 10, //单页显示结果条数
								pageIndex: 1, //页码
								city: '长沙', // 设置查询的城市为湖南长沙
								type: '医疗保健服务', //设置兴趣点类别
								map: that.map, //展现结果的地图实例
								panel: "panel", //参数值为你页面定义容器的 id 值<div id="my-panel"></div>，结果列表将在此容器中进行展示。
								autoFitView: true, //是否自动调整地图视野使绘制的 Marker 点都处于视口的可见范围
							})
						});

						// 如果还没开始导航 那么进入后自动搜索眼底医院
						if (this.startNavigation === false) {
							this.targetPlace = '眼底医院'
							this.searchPlace()
						}
					})
					.catch((e) => {
						console.log(e);
					});
			},

			// 地点搜索
			searchPlace(e, ownerInstance) {
				// 搜索以第二个参数范围内1000为半径的目标点
				if (this.targetPlace === '') {
					this.targetPlace = this.endAddress
				}
				let that = this;
				this.placeSearch.searchNearBy(this.targetPlace, this.nowLocation, 10000, function(status, result) {
					that.ownerInstance.callMethod('receiveShowSearchResult', {
						showSearchResult: true,
					})
					let doms = document.querySelectorAll('.poibox')
					for (let i = 0; i < doms.length; i++) {
						const index = doms[i].getAttribute('data-idx');
						doms[i].addEventListener("click", function() {
							let endLocation = result.poiList.pois[index].location
							let addressName = result.poiList.pois[index].name
							that.ownerInstance.callMethod('recevicePlaceSearchResult', {
								endLocation: endLocation,
								showModal: true,
								content: `确定要开始向${addressName}导航吗？`
							})
						})
					}
					that.targetPlace = ''
				})
			},
			// 开始步行导航
			startWalking() {
				AMapLoader.load({
						key: "bd1509b2c8644f4eb8ac504fbf4db856",
						version: "2.0",
						plugins: ["AMap.Walking",
							"AMap.MoveAnimation"
						],
					})
					.then((AMap) => {
						let that = this;
						// 步行导航配置
						var walkOption = {
							map: this.map,
							panel: "walkPanel"
						}
						var walking = new AMap.Walking(walkOption)
						walking.search(this.nowLocation, this.targetPlaceLocation, function(status, result) {
							// 修改startNavigation 改为导航过了
							that.startNavigation = true;
							// 呼叫父模块隐藏地点查询部分
							that.ownerInstance.callMethod('receiveShowAddressInfo', {
								showAddressInfo: false,
							})
							if (status === 'complete') {
								console.log('绘制成功')
								console.log(result)
							} else {
								console.log('绘制失败')
								console.log(result)
							}
						});
					})
					.catch((e) => {
						console.log(e);
					});
			}
		},
	}
</script>

<style scoped>
	@keyframes moveIn {
		0% {
			opacity: 0;
			transform: translateY(12px);
		}

		100% {
			opacity: 1;
			transform: translateY(0);
		}
	}

	uni-page-body {
		height: 100%;
	}

	#wrapper {
		width: 100%;
		height: 100%;
		position: relative;
	}

	#container {
		width: 100%;
		height: 800px;
	}

	#panel {
		position: fixed;
		background-color: white;
		max-height: 30%;
		overflow-y: scroll;
		bottom: 10px;
		width: 100%;
		animation: moveIn .3s cubic-bezier(.4, 0, .2, 1) forwards;
	}

	#walkPanel {
		position: absolute;
		background-color: white;
		max-height: 30%;
		overflow-y: scroll;
		top: 0;
		right: 0;
		width: 100%;
		transition: .3s;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
	}

	#addressInfo {
		position: absolute;
		width: 100%;
		height: 200px;
		z-index: 99;
		top: 0;
		border-radius: 0px 0px 5% 5%;
		background-color: white;
		animation: moveIn .3s cubic-bezier(.4, 0, .2, 1) forwards;
	}

	#addressForm {
		width: 80%;
		margin: 0 auto;
		padding: 0;
		margin-top: 5%;
	}

	#btn-group {
		margin-top: 2%;
		width: 100%;
		display: flex;
	}
</style>